using System;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEditor.IMGUI.Controls;
using UnityEngine;

namespace EditorExtensions
{
    public class TreeViewExample : EditorWindow
    {
        [MenuItem("EditorExtensions/12.TreeView/Open")]
        static void Open()
        {
            GetWindow<TreeViewExample>().Show();
        }

        [SerializeField] private TreeViewState m_TreeViewState;
        private SimpleTreeView m_SimpleTreeView;
        private SearchField m_SearchField;

        private void OnEnable()
        {
            if (m_TreeViewState == null)
            {
                m_TreeViewState = new TreeViewState();
            }

            m_SimpleTreeView = new SimpleTreeView(m_TreeViewState);
            m_SearchField = new SearchField();
            m_SearchField.downOrUpArrowKeyPressed += m_SimpleTreeView.SetFocusAndEnsureSelectedItem;
        }

        private void OnGUI()
        {
            GUILayout.BeginHorizontal();
            GUILayout.Space(100);
            GUILayout.FlexibleSpace();
            m_SimpleTreeView.searchString = m_SearchField.OnToolbarGUI(m_SimpleTreeView.searchString);
            GUILayout.EndHorizontal();

            var rect = GUILayoutUtility.GetRect(0, 10000, 0, 10000);
            m_SimpleTreeView.OnGUI(rect);
        }
    }

    public class SimpleTreeView: TreeView
    {
        public SimpleTreeView(TreeViewState state) : base(state)
        {
            Reload();
        }

        public SimpleTreeView(TreeViewState state, MultiColumnHeader multiColumnHeader) : base(state, multiColumnHeader)
        {
        }

        protected override TreeViewItem BuildRoot()
        {
            var root = new TreeViewItem(1, -1, "Root");
            var allItems = new List<TreeViewItem>()
            {
                new TreeViewItem(1, 0, "Animals1"),
                new TreeViewItem(2, 1, "Animals2"),
                new TreeViewItem(3, 2, "Animals3"),
                new TreeViewItem(4, 2, "Animals4"),
                new TreeViewItem(5, 2, "Animals5"),
                new TreeViewItem(6, 2, "Animals6"),
                new TreeViewItem(6, 1, "Material1"),
                new TreeViewItem(7, 2, "Material2"),
                new TreeViewItem(8, 2, "Material3"),
            };
            SetupParentsAndChildrenFromDepths(root, allItems);
            return root;
        }
    }

}
